import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '../stores/user';

const Login = () => import('../views/Login.vue');
const MainLayout = () => import('../layouts/MainLayout.vue');
const Dashboard = () => import('../views/Dashboard.vue');
const Timeline = () => import('../views/Timeline.vue');
const Stats = () => import('../views/Stats.vue');
const Gallery = () => import('../views/Gallery.vue');
const Settings = () => import('../views/Settings.vue');
const AIChat = () => import('../views/AIChat.vue');

const routes: RouteRecordRaw[] = [
  { path: '/login', name: 'login', component: Login },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'dashboard', component: Dashboard },
      { path: 'timeline', name: 'timeline', component: Timeline },
      { path: 'stats', name: 'stats', component: Stats },
      { path: 'gallery', name: 'gallery', component: Gallery },
      { path: 'ai-chat', name: 'ai-chat', component: AIChat },
      { path: 'settings', name: 'settings', component: Settings }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫执行:', to.path, to.meta);
  
  if (to.meta.requiresAuth) {
    // 检查是否有存储的token
    const token = localStorage.getItem('auth_token');
    console.log('检查token:', token);
    
    if (!token) {
      console.log('没有token，跳转到登录页');
      next('/login');
      return;
    }
    
    // 检查用户状态，如果没有登录状态，尝试恢复
    const userStore = useUserStore();
    if (!userStore.isLoggedIn) {
      console.log('用户状态未恢复，尝试恢复用户状态');
      const restored = await userStore.restoreUserState();
      if (!restored) {
        console.log('恢复用户状态失败，跳转到登录页');
        next('/login');
        return;
      }
    }
    
    console.log('有token且用户已登录，允许访问');
  }
  
  // 如果已登录用户访问登录页，重定向到首页
  if (to.path === '/login') {
    const token = localStorage.getItem('auth_token');
    if (token) {
      const userStore = useUserStore();
      // 如果用户状态未恢复，先尝试恢复
      if (!userStore.isLoggedIn) {
        const restored = await userStore.restoreUserState();
        if (restored) {
          console.log('恢复用户状态成功，重定向到首页');
          next('/');
          return;
        }
      } else {
        console.log('已登录用户访问登录页，重定向到首页');
        next('/');
        return;
      }
    }
  }
  
  next();
});

export default router;


